package de.htw_saar.mad_ea;

import java.text.DecimalFormat;
import java.util.EmptyStackException;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import de.congrace.exp4j.ExpressionBuilder;
import de.congrace.exp4j.UnknownFunctionException;
import de.congrace.exp4j.UnparsableExpressionException;

public class CalculatorOps {
	private TextView display;
	private boolean hasSeparator;
	private boolean isPreviousOperator;
	private static CalculatorOps calc;

	public static CalculatorOps getInstance(Activity activity) {
		if (calc == null)
			calc = new CalculatorOps(activity);
		return calc;
	}

	private CalculatorOps(Activity activity) {
		display = (TextView) activity.findViewById(R.id.display);
	}

	DecimalFormat deciformat = new DecimalFormat("0.#####");

	public void write_number(View v) {
		switch (v.getId()) {
		case R.id.button_sep:
			if (!hasSeparator) {
				if (isPreviousOperator) {
					display.append("0");
				}
				display.append(((Button) v).getText());
			}
			hasSeparator = true;
			isPreviousOperator = true;
			break;
		default:
			if (display.getText().equals("0")) {
				display.setText(((Button) v).getText());
			} else {
				display.append(((Button) v).getText());
			}
			isPreviousOperator = false;
		}
	}

	public void write_operator(View v) {
		if (isPreviousOperator) {
			display.setText(display.getText().subSequence(0,
					display.getText().length() - 1));
		}
		display.append(((Button) v).getText());
		isPreviousOperator = true;
		hasSeparator = false;
	}

	public void clear(View v) {
		display.setText("0");
		hasSeparator = false;
		isPreviousOperator = false;
	}

	public void delete(View v) {
		CharSequence temp = display.getText();
		if (temp.length() != 0)
			temp = temp.subSequence(0, display.getText().length() - 1);
		if (temp.length() == 0)
			temp = "0";
		switch (temp.charAt(temp.length() - 1)) {
		case '*':
		case '/':
		case '+':
		case '-':
			isPreviousOperator = true;
			hasSeparator = false;
			break;
		case '.':
			isPreviousOperator = true;
			hasSeparator = true;
			break;
		default:
			isPreviousOperator = false;
			break;
		}
		display.setText(temp);
	}

	public void solution(View v) {
		try {
			double solution = new ExpressionBuilder(display.getText()
					.toString()).build().calculate();

			display.setText(deciformat.format(solution));
		} catch (UnknownFunctionException e) {
			e.printStackTrace();
		} catch (EmptyStackException e) {
			e.printStackTrace();
		} catch (UnparsableExpressionException e) {
			e.printStackTrace();
		}
	}

	public void writer_operator_extended(View v) {
		if (isPreviousOperator) {
			display.append(((Button) v).getText());
			isPreviousOperator = true;
			hasSeparator = false;
		}
	}
}
